# coding=utf-8
import pika
import json
import time
# 设置MQ环境
env = "pt_test"

if env == "localhost":
    mq_info = {
        "username": "guanfuchang",
        "password": "12345678",
        "host": "localhost",
        "virtual_host": "/vhost_qa"
    }
elif env == "pt_test":
    mq_info = {
        "username": "",
        "password": "",
        "host": "",
        "virtual_host": ""
    }


def get_connection():
    """
    获取MQ连接
    :return:
    """
    # 连接MQ
    user_pwd = pika.PlainCredentials(username=mq_info.get("username"), password=mq_info.get("password"))
    connection = pika.BlockingConnection(pika.ConnectionParameters(host=mq_info.get("host"),
                                                                   virtual_host=mq_info.get("virtual_host"),
                                                                   credentials=user_pwd))
    return connection


# 获取MQ连接
connection = get_connection()

# 在连接上创建一个频道CHANNEL
channel = connection.channel()

exchange_name='rfchina.platform.secure'
# 声明一个交换机并声明exchange的类型为模糊匹配。
channel.exchange_declare(exchange=exchange_name, exchange_type='topic', durable=True)

# 创建一个队列，exclusive=True（唯一性）表示在消费者与rabbitmq断开连接时，该队列会自动删除掉
result = channel.queue_declare(exclusive=True)

# 因为rabbitmq要求新队列名必须是与现存队列名不同，所以为保证队列的名字是唯一的，method.queue方法会随机创建一个队列名字
queue_name = result.method.queue

# 将交换机direct_logs与接收消息的队列绑定。表示生产者将消息发给交换机direct_logs，direct_logs将消息发给随机队列queue，消费者在随机队列queue中取消息
channel.queue_bind(exchange=exchange_name,
                   queue=queue_name,
                   routing_key='#',  # 该消费者绑定的关键字。‘#’匹配所有字符，‘*’匹配一个单词
                   )

print('[消费者] Waiting for logs. To exit press CTRL+C')


# 定义一个回调函数，用来接收生产者发送的消息

def callback(ch, method, properties, body):
    print("Start.....%s........."%time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    print("[method]:",method)
    print("[body] Received %s" % json.loads(bytes.decode(body,encoding="utf8"),encoding="utf8"))
    print("End................................")
    print("")

# 开启一个死循环接受MQ消息。
channel.basic_consume(callback,  # 调用回调函数，从队列里取消息
                      queue=queue_name,  # 指定取消息的队列名
                      no_ack=True,  # 设置为消费者不给rabbitmq回复确认。
                      )

# 开始循环取消息
channel.start_consuming()
